﻿using Lucene.Net.Analysis.PanGu;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZHJ.PerfectOA.Model;
using ZHJ.PerfectOA.WebApp.Models;

namespace ZHJ.PerfectOA.WebApp.Controllers
{
    public class SearchController : BaseController
    {
        //
        // GET: /Search/

        IBLL.IBooksService BookService { get; set; }
        IBLL.IKeyWordsRankService KeyWordsRankService { set; get; }
        IBLL.ISearchDetailsService SearchDetailsService { set; get; }

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 搜索或者创建索引库
        /// </summary>
        /// <returns></returns>
        public ActionResult SearchContent()
        {
            //如果form表单中有多个submit，只会将你所单击的sumbit的value值提交到服务端，其它按钮的value是不提交的。
            if (!string.IsNullOrEmpty(Request["btnSearch"]))
            {
                //实现查询功能
                List<ViewModelSearchResult> list = SearchMsg();
                ViewData["searchResult"] = list;
                ViewData["searchWhere"] = Request["txtMsg"];
                return View("Index");
            }
            else
            {
                //将数据写到Lucene.Net
                CreateIndexContent();
            }
            return Content("ok");
        }

        /// <summary>
        /// 搜索功能
        /// </summary>
        /// <returns></returns>
        private List<ViewModelSearchResult> SearchMsg()
        {
            string indexPath = @"C:\lucenedir";
            string[] kw = Common.WebCommon.GetPanGuSplitWord(Request["txtMsg"]).ToArray();
            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
            IndexReader reader = IndexReader.Open(directory, true);
            IndexSearcher searcher = new IndexSearcher(reader);
            //搜索条件
            PhraseQuery query = new PhraseQuery();
            foreach (string word in kw)//先用空格，让用户去分词，空格分隔的就是词“计算机   专业”
            {
                query.Add(new Term("Msg", word));
            }
            //query.Add(new Term("body","语言"));--可以添加查询条件，两者是add关系.顺序没有关系.
            //query.Add(new Term("body", "大学生"));
            // query.Add(new Term("body", kw));//body中含有kw的文章
            query.SetSlop(100);//多个查询条件的词之间的最大距离.在文章中相隔太远 也就无意义.（例如 “大学生”这个查询条件和"简历"这个查询条件之间如果间隔的词太多也就没有意义了。）
            //TopScoreDocCollector是盛放查询结果的容器
            TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);
            searcher.Search(query, null, collector);//根据query查询条件进行查询，查询结果放入collector容器
            ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs;//得到所有查询结果中的文档,GetTotalHits():表示总条数   TopDocs(300, 20);//表示得到300（从300开始），到320（结束）的文档内容.
            //可以用来实现分页功能
            List<ViewModelSearchResult> list = new List<ViewModelSearchResult>();
            for (int i = 0; i < docs.Length; i++)
            {
                //
                //搜索ScoreDoc[]只能获得文档的id,这样不会把查询结果的Document一次性加载到内存中。降低了内存压力，需要获得文档的详细内容的时候通过searcher.Doc来根据文档id来获得文档的详细内容对象Document.
                int docId = docs[i].doc;//得到查询结果文档的id（Lucene内部分配的id）
                Document doc = searcher.Doc(docId);//找到文档id对应的文档详细信息
                ViewModelSearchResult viewModelResult = new ViewModelSearchResult();
                viewModelResult.Id = doc.Get("Id");
                viewModelResult.Title = doc.Get("Title");
                viewModelResult.Msg = Common.WebCommon.CreateHightLight(Request["txtMsg"], doc.Get("Msg"));
                viewModelResult.Url = "/Search/ShowDetail/?id=" + doc.Get("Id");
                list.Add(viewModelResult);
                 
            }

            //搜索成功后将搜索的内容添加到数据库中，作为搜索常用词
            SearchDetails searchDetails = new SearchDetails();
            searchDetails.KeyWords = Request["txtMsg"];
            searchDetails.Id = Guid.NewGuid();
            searchDetails.SearchDateTime = DateTime.Now;
            SearchDetailsService.AddEntity(searchDetails);
            return list;
        }
        /// <summary>
        /// 将数据写到Lucene.Net中
        /// </summary>
        private void CreateIndexContent()
        {
            
        }

        public ActionResult GetSearchMsg()
        {
            string term = Request["term"];
            List<string> list = KeyWordsRankService.GetTerm(term);
            return Json(list.ToArray(), JsonRequestBehavior.AllowGet);
        }
    }
}
